﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Text;

public partial class SchemaDB_ShowError : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        // get error hash
        var hash = this.Request.Params["Id"];

        if (string.IsNullOrEmpty(hash))
            throw new ArgumentException("missing 'Id' parameter in request");

        // load error
        using (var conn = new SqlConnection(Settings.ConnectionString))
        {
            conn.Open();

            var cmd = new SqlCommand()
            {
                Connection = conn,
                CommandType = System.Data.CommandType.Text,
                CommandText = "select top 1 Message,StackTrace,ErrorType,ClassName,MethodName,ErrorCount from ErrorsGrouped where ErrorHash=@hash"

            };

            cmd.Parameters.AddWithValue("@hash", hash);

            using (var r = cmd.ExecuteReader())
            {
                if (!r.Read())
                    throw new ArgumentException("query parameter 'Id' does not match an error hash id");

                // set values
                this.Message.InnerText = r.GetString(0);

                {
                    var st = r.GetSqlString(1);

                    if (st.IsNull)
                        this.StackTrace.InnerText = "<none>";
                    else
                        this.StackTrace.InnerText = st.Value;
                }
                
                this.ErrorType.InnerText = r.GetString(2);
                this.ClassName.InnerText = r.GetString(3);
                this.MethodName.InnerText = r.GetString(4);
                this.ErrorCount.InnerText = r.GetInt32(5).ToString();
            }

            // load versions
            var cmd2 = new SqlCommand()
            {
                Connection = conn,
                CommandType = System.Data.CommandType.Text,
                CommandText = "select VersionStr from ErrorsGrouped inner join Releases on ReleaseId=Id where ErrorHash=@hash order by ReleaseId desc"
            };

            cmd2.Parameters.AddWithValue("@hash", hash);

            using (var r = cmd2.ExecuteReader())
            {
                var sb = new StringBuilder();

                while (r.Read())
                {
                    if (sb.Length > 0)
                        sb.Append("; ");

                    sb.Append(r.GetString(0));
                }

                this.Versions.InnerText = sb.ToString();
            }
        }

    }
}
